import sys
import os

# 获取当前文件的绝对路径
current_file_path = os.path.abspath(__file__)
# 获取当前文件所在的目录
current_dir = os.path.dirname(current_file_path)
# 获取上级目录
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
# import main.Ui_main
import Ui_main

from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QLabel, QLineEdit,QTextEdit
from PyQt6.QtCore import QThread, pyqtSignal
import socket
import threading
from datetime import datetime
# import main.Ui_main
def extract_ip():#获取本机IP
    st = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        st.connect(('10.255.255.255', 1))
        IP = st.getsockname()[0]
    except Exception:
        IP = '127.0.0.1'
    finally:
        st.close()
    return IP
def get_time():#获取本机时间
        current_time = datetime.now().strftime("%H:%M:%S.%f")[:-3]
        return current_time
class MainWindow(QMainWindow,Ui_main.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.hostip=extract_ip()
        self.input_hostip.setText(self.hostip+':12345')
        self.btn_server.clicked.connect(self.start_server)
        self.flag_server=False
        self.server_thread = ServerThread(self.hostip, 12345)
        self.server_thread.received_data.connect(self.show_received_data)
        self.server_thread.server_log.connect(self.server_log)
        self.server_thread.update_clients_list.connect(self.update_clients_list)
        self.btn_clear.clicked.connect(self.fuc_clear)
    def start_server(self):#启动服务器
        if self.flag_server==False:
            self.btn_server.setText("关闭服务器")
            self.flag_server=True
            self.server_thread.start()
        else:
            self.btn_server.setText("开启服务器")
            self.flag_server=False
            self.server_thread.stop()

    def signalCall_print(self, text=""):#显示在文本框
            self.textBrowser.append(get_time()+"  "+text)  
    def show_received_data(self, client_address,data):
        self.signalCall_print(f"收到来自 {client_address} 的数据： {data}")
    def server_log(self, txt):
        self.textBrowser.append(txt)
    def update_clients_list(self, client_info):
        item_text=client_info[0]+':'+str(client_info[1])
        if self.com_clients.findText(item_text) == -1:#没有找到
            self.com_clients.addItem(item_text)           
        else:
            self.com_clients.removeItem(self.com_clients.findText(item_text))
    #region # 接收数据清空
    def fuc_clear(self, text=""):
        self.textBrowser.clear()
    #endregion        

class ServerThread(QThread):
    received_data = pyqtSignal(tuple,str)
    server_log = pyqtSignal(str)
    update_clients_list = pyqtSignal(tuple)
    stop_signal = pyqtSignal()

    def __init__(self, host, port):
        super().__init__()
        self.host = host
        self.port = port
        self.client_sockets=[]

    def run(self):
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.bind((self.host, self.port))
        self.server_socket.listen(5)
        self.flag_run=True
        self.server_log.emit("服务器已启动，等待客户端连接...")

        while self.flag_run:
            try:
                client_socket, client_address = self.server_socket.accept()
                self.client_sockets.append(client_socket)
                print(self.client_sockets)
                self.server_log.emit(f"客户端 {client_address} 已连接")
                self.update_clients_list.emit(client_address)#更新界面列表
                threading.Thread(target=self.handle_client, args=(client_socket,client_address)).start()
            except:
                self.server_log.emit("服务器已关闭")
                # client_socket.close()
            
    def stop(self):
        self.flag_run=False
        self.server_socket.close()
        # 关闭所有连接设备
        # for i in range(0,len(self.client_sockets)):
        #     try:
        #         self.client_sockets[i].send(b"exit")
        #         self.client_sockets[i].close()
        #     except:
        #         break
        # self.client_sockets=[]

    def handle_client(self, client_socket,client_address):
        while True:
            try:
                data = client_socket.recv(1024).decode('gb2312')
                if not data:
                    break
                self.received_data.emit(client_address,data)
            except Exception as e:
                print(f"客户端 {client_address} 断开连接，原因： {e}")
                break
        client_socket.close()
        self.server_log.emit(f"客户端 {client_address} 断开连接")
        self.client_sockets.remove(client_socket)
        self.update_clients_list.emit(client_address)#更新界面列表

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec())
